package com.jeff.android.lab.compat.ten;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.duff.download.okdownload.LiteDownload;
import com.duff.download.okdownload.interfaces.LiteDownloadListener;
import com.jeff.android.lab.BaseFragment;
import com.jeff.android.lab.R;
import com.jeff.permission.CheckPermission;
import com.jeff.permission.PermissionItem;
import com.jeff.permission.PermissionListener;
import com.jeff.utils.FileUtil;
import com.jeff.utils.ImageUtil;
import com.jeff.utils.LogUtil;
import com.jeff.utils.security.MD5Util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author: dingfeng
 * @date: 2020-04-16
 * @since: 1.0.0
 **/
public class Android10CompatFragment extends BaseFragment {

    private final static int GALLERY_OPEN_REQUEST_CODE = 1000;

    @BindView(R.id.image) ImageView mImageView;

    @Override
    protected int getRootLayout() {
        return R.layout.compat_fragment_android10;
    }

    @OnClick(R.id.btn_save_image_album)
    void saveImage2Album() {
        CheckPermission.instance(mContext).check(new PermissionItem(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE),
                new PermissionListener() {
                    @Override
                    public void permissionGranted() {
                        Drawable drawable = getResources().getDrawable(R.drawable.icon_libai);
                        Bitmap bitmap = ImageUtil.drawable2Bitmap(drawable);
                        save(bitmap, System.currentTimeMillis() + ".jpg", Bitmap.CompressFormat.JPEG);
                    }

                    @Override
                    public void permissionDenied() {

                    }
                });
    }

    @OnClick(R.id.btn_open_gallery)
    void openGallery() {
        CheckPermission.instance(mContext).check(new PermissionItem(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE),
                new PermissionListener() {
                    @Override
                    public void permissionGranted() {
                        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        intent.setType("image/*");
                        startActivityForResult(intent, GALLERY_OPEN_REQUEST_CODE);
                    }

                    @Override
                    public void permissionDenied() {

                    }
                });
    }

    @OnClick(R.id.btn_download_image)
    void downloadImage() {
        final String url = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1357518075,2207145940&fm=26&gp=0.jpg";
        final String name = MD5Util.get32MD5String(url) + ImageUtil.JPG;
        final String path = mContext.getExternalCacheDir().getAbsolutePath() + File.separator + name;
        LogUtil.d(TAG, "[downloadImage] path = " + path);
        downloadImage(url, path);
    }

    private void save(Bitmap bitmap, String name, Bitmap.CompressFormat format) {
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/*");

        // Q 以上保存到公共目录
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM); // DIRECTORY_DCIM、DIRECTORY_PICTURES、DIRECTORY_MOVIES、DIRECTORY_MUSIC
        } else {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "123" + File.separator + name;
            values.put(MediaStore.MediaColumns.DATA, path);
            values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
            values.put(MediaStore.MediaColumns.DATE_MODIFIED, System.currentTimeMillis() / 1000);
        }

        ContentResolver resolver = getActivity().getContentResolver();

        Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);


        OutputStream outputStream = null;

        try {
            outputStream = resolver.openOutputStream(uri);
            if (outputStream != null) {
                bitmap.compress(format, 100, outputStream);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void getImageUri(Context context) {
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, "");
        if (cursor != null) {
            while (cursor.moveToNext()) {
                long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
                Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
            }
            cursor.close();
        }
    }

    /**
     * 使用文件描述符解析 Uri 图片
     * */
    private Bitmap getBitmapFromUri(Uri uri) {
        ParcelFileDescriptor fd = null;
        Bitmap bitmap = null;
        try {
            fd = getActivity().getContentResolver().openFileDescriptor(uri, "r");
            if (fd != null) {
                bitmap = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fd != null) fd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    private void downloadImage(String url, String path) {
        LiteDownload.download(url, path, new LiteDownloadListener() {
            @Override
            public void onSuccess(File file) {
                Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                if (bitmap != null) {
                    save(bitmap, FileUtil.getFileName(path), Bitmap.CompressFormat.JPEG);
                }
            }

            @Override
            public void onError(Exception e) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GALLERY_OPEN_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            LogUtil.d(TAG, "选择图片：" + uri.toString());

            Glide.with(this).load(uri)
                    .into(mImageView);
        }
    }


}
